/**
 * 
 */
package com.zufangbao.earth.web.controller;

import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.demo2do.core.utils.JsonUtils;
import com.zufangbao.earth.ViewEntry;
import com.zufangbao.earth.entity.security.Principal;
import com.zufangbao.earth.handler.CookieHandler;
import com.zufangbao.earth.handler.ViewSpecHandler;
import com.zufangbao.earth.service.PrincipalService;
import com.zufangbao.earth.web.controller.SettingControllerSpec.IAppBriefList;
import com.zufangbao.earth.web.controller.SettingControllerSpec.ISaveAppSetting;
import com.zufangbao.gluon.handler.ResultHandler;
import com.zufangbao.gluon.spec.earth.GlobalSpec4Earth;
import com.zufangbao.gluon.spec.global.GlobalMsgSpec;
import com.zufangbao.sun.entity.company.corp.App;
import com.zufangbao.sun.service.AppService;

/**
 * @author wukai
 *
 */
@Controller
@RequestMapping(SettingControllerSpec.NAME)
public class SettingController {
	
	@Autowired
	private AppService appService;
	
	@Autowired
	private PrincipalService principalService;
	
	@Autowired
	private CookieHandler cookieHandler;
	
	@Autowired
	private ResultHandler resultHandler;
	
	@Autowired
	private ViewSpecHandler viewSpecHandler;
	
	@RequestMapping(IAppBriefList.NAME)
	public String appBrieflist(String targetUrl,Model model) {
		
		List<App> apps = appService.loadAll(App.class);
		
		model.addAttribute(apps);
		
		model.addAttribute(IAppBriefList.PARAM_TARGET_URL,targetUrl);
		
		return IAppBriefList.VIEW_NAME;
	}
	@RequestMapping(value = ISaveAppSetting.NAME, method = RequestMethod.POST)
	public String onSaveApp(HttpServletResponse response,String appId,String targetUrl) {
		
		try {
			Principal principal = principalService.getPrincipal(appId);
			
			ViewEntry viewCategory = new ViewEntry(principal.getName(), principal.getAuthority());
			
			cookieHandler.addCookie(GlobalSpec4Earth.PARAM_VIEW_CATEGORY, JsonUtils.toJsonString(viewCategory), response);
			
			return "redirect:" + targetUrl;
			
		} catch (Exception e) {
			
			return resultHandler.errorJsonResult(GlobalMsgSpec.GeneralErrorMsg.MSG_NO_AUTHORITY);
		}
	}
}
